package leetcode

import "strings"

func wordPattern(pattern string, s string) bool {
	lst := strings.Fields(s)
	n := len(pattern)
	if n != len(lst) {
		return false
	}

	p2s := make(map[byte]string, n)
	s2p := make(map[string]byte, n)
	for i := 0; i < n; i++ {
		c := pattern[i]
		w := lst[i]
		fW, ok1 := p2s[c]
		fC, ok2 := s2p[w]
		if (ok1 && !ok2) || (!ok1 && ok2) {
			return false
		} else if ok1 && ok2 && (fW != w || fC != c) {
			return false
		} else if !ok1 && !ok2 {
			p2s[c] = w
			s2p[w] = c
		}
	}

	return true
}
